package net.kong.sns.rest.client.user;

import net.kong.sns.rest.client.method.JsonMethodInvokeBase;
import net.kong.sns.rest.client.model.UserInfo;
import net.kong.sns.rest.client.model.UserInfoImpl;
import net.kong.sns.rest.client.rest.HttpResponseContent;
import net.kong.sns.rest.client.InvalidResponseException;
import net.kong.sns.rest.client.KongApiMethod;
import net.kong.org.springframework.util.StringUtils;

import java.util.Set;
import java.util.HashSet;
import java.util.Arrays;
import java.util.List;
import java.util.Map;

/**
 * @author <a href="mailto:lanhuai@gmail.com">Ning Yubin</a>
 * @version $Id: UserInfoMethodInvoke.java,v 1.3 2009/11/04 17:17:38 ningyubin Exp $
 */
public class UserInfoMethodInvoke extends JsonMethodInvokeBase<UserInfo> {
    
    public UserInfoMethodInvoke(long userId, String sessionKey) {
        super(KongApiMethod.USERS_GET_INFO, sessionKey);
        setParameter("user_ids", String.valueOf(userId));
        setParameter("fields", StringUtils.arrayToCommaDelimitedString(UserInfo.Field.values()));
    }

    public UserInfoMethodInvoke(long userId, UserInfo.Field[] fields, String sessionKey) {
        super(KongApiMethod.USERS_GET_INFO, sessionKey);
        setParameter("user_ids", String.valueOf(userId));
        setParameter("fields", StringUtils.arrayToCommaDelimitedString(fields));
    }

    @Override
    protected UserInfo processJsonResponse(HttpResponseContent responseData) throws InvalidResponseException {
        String response = responseData.getBody();
        Set<String> initializedFields = new HashSet<String>();

        String fields = getParameter("fields");
        if (fields != null) {
            initializedFields.addAll(Arrays.asList(fields.split(",")));
        }
        Object o = reader.read(response);
        List<Map<String, Object>> userList = (List<Map<String, Object>>) o;
        if (userList.size() > 0) {
            UserInfoImpl userInfo = new UserInfoImpl();
            userInfo.initialize(userList.get(0), initializedFields);
            return userInfo;
        }
        return null;
    }
}
